<template>
  <a-modal :width="1300" v-model:visible="showEditDialog" title="创建交货单" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <p style="margin-bottom: 10px">注意：相同供应商+相同收货仓+相同的结算方式归到一个交货单</p>
    <a-table
      class="table-normal-line s"
      ref="tableRef"
      row-key="key"
      :data="purchaseOrders"
      :span-method="spanMethodAll"
      :scroll="{
        y: 'calc(84vh - 180px)',
      }"
      :columns="tableColumns"
      :expandable="expandable"
      :loading="tableLoading"
      :default-expand-all-rows="true"
      size="mini"
      :bordered="false"
      :pagination="false"
    >
      <template #columns>
        <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
          <template #title v-if="item.tip">
            <a-popover>
              <template #content>
                <p v-for="(str, i) in item.tip.split('--')" :key="i" style="max-width: 500px">{{ str }}</p>
              </template>
              <p>
                <span>{{ item.title }}</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template v-if="item.dataIndex == 'sku'" #cell="{ record }">
            <div class="order-w flex">
              <div class="order-detail-item" style="width: 240px">
                <p><span class="label">供应商：</span>{{ record.supplierName }}</p>
              </div>
              <div class="order-detail-item" style="width: 240px">
                <p><span class="label">收货仓：</span>{{ record.warehouseName }}({{ record.warehouseCode }})</p>
              </div>
              <div class="order-detail-item" style="width: 240px">
                <p><span class="label">结算方式：</span>{{ settleTypeMap[record.settleType] }}</p>
              </div>
            </div>
          </template>
        </a-table-column>
      </template>
      <template #expand-row="{ record }">
        <a-table class="table-two-line" :bordered="{ cell: true }" row-class="child-row" :show-header="false" row-key="id" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
          <template #columns>
            <a-table-column :width="10" />
            <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template #cell="option">
                <!-- 产品 -->
                <div v-if="item.dataIndex == 'sku'" class="flex-c">
                  <ImgPopover :src="option.record.productImg">
                    <template #con>
                      <a-image width="50" height="50" fit="contain" :src="option.record.productImg" />
                    </template>
                  </ImgPopover>
                  <a-popover position="bottom">
                    <template #content>
                      <div style="max-width: 400px">
                        <p>品名：{{ option.record.productName }}</p>
                        <p>SKU：{{ option.record.sku }}</p>
                        <p>SPU：{{ option.record.spu }}</p>
                        <p>类目：{{ option.record.cateName }}</p>
                        <p style="margin-bottom: 20px">规格：{{ getProductSpecs(option.record) }}</p>
                        <p v-for="(prop, k) in option.record.purchaseSpecsArr" :key="k">
                          <span>{{ prop.name }}：</span>
                          <span>{{ getStrVal(prop.purchaseValue) }}</span>
                        </p>
                      </div>
                    </template>
                    <div style="margin-left: 5px; flex: 1">
                      <p class="highlight">{{ option.record.sku }}</p>
                      <TextLimit :val="getProductSpecs(option.record)" :rows="1" />
                    </div>
                  </a-popover>
                </div>
                <!-- 交货数 -->
                <div v-else-if="item.dataIndex == 'deliveryAmt'" class="cell flex-c" style="width: 80px">
                  <a-input-number :precision="0" :min="0" v-model="option.record.deliveryAmt" style="width: 60px" placeholder="" hide-button />
                  <icon-double-down v-if="showBatchIcon(record.key, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'deliveryAmt', option.rowIndex, record.key)" />
                </div>
                <!-- 主材重量 -->
                <div v-else-if="item.dataIndex == 'materialWeight'" class="cell flex-c" style="width: 80px">
                  <a-input-number :precision="0" :min="0" v-model="option.record.materialWeight" style="width: 60px" placeholder="" hide-button />
                  <icon-double-down v-if="showBatchIcon(record.key, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'materialWeight', option.rowIndex, record.key)" />
                </div>
                <!-- 材质金额 -->
                <span v-else-if="item.dataIndex == 'materialAmount'">￥{{ (Number(option.record.materialWeight || 0) * Number(option.record.materialPrice || 0)).toFixed(2) }}</span>
                <!-- 产品金额 -->
                <span v-else-if="item.dataIndex == 'productAmount'">￥{{ (Number(option.record.deliveryAmt || 0) * Number(option.record.productPrice || 0)).toFixed(2) }}</span>
                <!-- 工费 -->
                <span v-else-if="item.dataIndex == 'laborAmount'">￥{{ (Number(option.record.deliveryAmt || 0) * Number(option.record.laborPrice || 0)).toFixed(2) }}</span>
                <!-- 其他费用 -->
                <div v-else-if="item.dataIndex == 'otherAmount'" class="cell flex-c" style="width: 80px">
                  <a-input-number :precision="2" :min="0" v-model="option.record.otherAmount" style="width: 60px" placeholder="" hide-button />
                  <icon-double-down v-if="showBatchIcon(record.key, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'otherAmount', option.rowIndex, record.key)" />
                </div>
                <!-- 合计金额 -->
                <span v-else-if="item.dataIndex == 'totalAmount'">￥{{ getTotalAmount(option.record).toFixed(2) }}</span>
                <!-- 税率 -->
                <template v-else-if="item.dataIndex == 'rate'">
                  <p>
                    <span>{{ Number(option.record.rate || 0) }}</span>
                    <span>%</span>
                  </p>
                  <p class="highlight">{{ option.record.priceType === 1 ? '含税' : '不含税' }}</p>
                </template>
                <!-- 单件货值 -->
                <span v-else-if="item.dataIndex == 'value'">￥{{ getTotalValue(option.record).toFixed(2) }}</span>
                <p v-else-if="['materialPrice', 'laborPrice', 'productPrice'].includes(item.dataIndex)">￥{{ option.record[item.dataIndex] }}</p>
                <p v-else>{{ option.record[item.dataIndex] }}</p>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { createPurchaseDelivery } from '@/api/purchaseApplication'
  import { parseJson, getStrVal } from '@/utils'
  import { cloneDeep } from 'lodash-es'
  onMounted(() => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: () => [],
    },
  })
  const tableColumns: Array<any> = [
    {
      title: '产品',
      dataIndex: 'sku',
      width: 160,
    },
    {
      title: '申购单号',
      dataIndex: 'planNo',
      width: 120,
    },
    {
      title: '采购员',
      dataIndex: 'purchaseUname',
      width: 60,
    },
    {
      title: '需求人',
      dataIndex: 'salesmanName',
      width: 60,
    },
    {
      title: '采购数量',
      dataIndex: 'purchaseAmt',
      width: 60,
    },
    {
      title: '已收货数',
      dataIndex: 'deliveryRealAmt',
      tip: '该采购已经签收的数量',
      width: 70,
    },
    {
      title: '未交货数',
      dataIndex: 'deliveryStayAmt',
      tip: '未交货数=采购数量-已收货数-已交货未签收数-截单数',
      width: 70,
    },

    {
      title: '材质单价(元/g)',
      dataIndex: 'materialPrice',
      width: 60,
    },

    {
      title: '产品单价',
      dataIndex: 'productPrice',
      width: 60,
    },
    {
      title: '工费单价',
      dataIndex: 'laborPrice',
      width: 60,
    },
    {
      title: '本次交货数',
      dataIndex: 'deliveryAmt',
      tip: '本次交货数=未交货数+（未交货数*0.3向上取整），--未交货数*0.3如果<=2则默认为3，也就是说供应商可以多发3件以上的货。',
      width: 100,
    },
    {
      title: '交货材质重(g)',
      dataIndex: 'materialWeight',
      tip: '交货材质重量是只本次交货材质净重量（该值针对的是首饰等以贵金属作为原材料的产品）',
      width: 100,
    },
    {
      title: '材质金额',
      dataIndex: 'materialAmount',
      tip: '材质金额=交货材质重量*材质单价',
      width: 70,
    },
    {
      title: '产品金额',
      dataIndex: 'productAmount',
      tip: '产品金额=产品单价*本次交货数',
      width: 70,
    },
    {
      title: '工费',
      dataIndex: 'laborAmount',
      tip: '工费=工费单价*本次交货数',
      width: 70,
    },
    {
      title: '其他费用',
      dataIndex: 'otherAmount',
      tip: '其他费用：本次交货产生的其他费用',
      width: 100,
    },
    {
      title: '合计金额',
      dataIndex: 'totalAmount',
      tip: '合计金额=材质金额+产品金额+工费+其他费用',
      width: 80,
    },
    {
      title: '税率',
      dataIndex: 'rate',
      width: 60,
    },
    {
      title: '单件货值',
      dataIndex: 'value',
      tip: '含税货值=合计金额/本次交货数不含税货值={合计金额-（合计金额-税率）}/本次交货数',
      width: 80,
    },
  ]

  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const settleTypeMap = {
    1: '月结',
    2: '现货',
    3: '现款',
  }
  const showEditDialog = ref(props.isShow)
  const purchaseOrders = ref<Array<any>>([])
  const submitLoading = ref(false)
  const tableLoading = ref(false)

  // 添加初始化数据
  async function setDefaultData() {
    let _list = cloneDeep(props.list)
    const orderMap: any = {}
    _list.forEach((el: any) => {
      let key = el.supplierCode + el.warehouseCode + el.settleType
      if (!orderMap[key]) {
        orderMap[key] = {
          key: key,
          warehouseName: el.warehouseName,
          warehouseCode: el.warehouseCode,
          supplierCode: el.supplierCode,
          supplierName: el.supplierName,
          supplierId: el.supplierId,
          settleType: el.settleType,
          deductionType: el.deductionType,
          outWarehouseCode: el.outWarehouseCode,
          outWarehouseName: el.outWarehouseName,
          billItems: [],
        }
      }
      let purchaseSpecs = el.purchaseSpecs ? parseJson(el.purchaseSpecs, {}) : {}
      el.purchaseSpecsArr = Object.values(purchaseSpecs)
      orderMap[key].billItems.push(el)
    })
    purchaseOrders.value = Object.values(orderMap)
    expandable.value.expandedRowKeys = purchaseOrders.value.map((el: any) => el.key)
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'sku') {
      return { rowspan: 1, colspan: 19 }
    }
  }

  //设置全局
  async function setGlobal(item: any, key: string, rowIndex: number, parentId: string) {
    let parentIndex = purchaseOrders.value.findIndex((el: any) => el.key === parentId)
    const newVal = item[key]
    purchaseOrders.value.forEach((el: any, index: number) => {
      if (index === parentIndex) {
        el.billItems.forEach((child: any, j: number) => {
          if (j > rowIndex) child[key] = newVal
        })
      } else if (index > parentIndex) {
        el.billItems.forEach((child: any) => {
          child[key] = newVal
        })
      }
    })
  }

  // 是否显示批量编辑按钮
  function showBatchIcon(parentId: string, childIndex: number) {
    let parentIndex = purchaseOrders.value.findIndex((el: any) => el.key === parentId)
    let parentLen = purchaseOrders.value.length
    return !(parentIndex === parentLen - 1 && childIndex === purchaseOrders.value[parentIndex].billItems.length - 1)
  }
  // 获取合计金额
  function getTotalAmount(row: any) {
    let materialAmount = Number(row.materialWeight || 0) * Number(row.materialPrice || 0)
    let productAmount = Number(row.deliveryAmt || 0) * Number(row.productPrice || 0)
    let laborAmount = Number(row.deliveryAmt || 0) * Number(row.laborPrice || 0)
    let otherAmount = Number(row.otherAmount || 0)
    return materialAmount + productAmount + laborAmount + otherAmount
  }
  // 获取单件货值
  function getTotalValue(row: any) {
    let totalAmount = getTotalAmount(row)
    let rateAmount = row.priceType === 0 ? 0 : (totalAmount * Number(row.rate || 0)) / 100
    return row.deliveryAmt ? (totalAmount - rateAmount) / row.deliveryAmt : 0
  }
  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  // 保存
  async function submitData() {
    let deliveryParams: Array<any> = []
    purchaseOrders.value.forEach((el: any) => {
      let obj: any = cloneDeep(el)
      delete obj.key
      obj.billItems = el.billItems.map((item: any) => {
        let billObj: any = {
          materialWeight: item.materialWeight,
          otherAmount: item.otherAmount,
          deliveryAmt: item.deliveryAmt,
          purchaseId: item.billId,
          purchaseItemId: item.id,
          remark: item.remark,
          settleType: item.settleType,
        }

        return billObj
      })
      deliveryParams.push(obj)
    })
    console.log(deliveryParams)

    let res: any = await createPurchaseDelivery({ deliveryParams })
    if (!res) return false
    Message.success('创建成功')
    emit('success')
    closedDialog()
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
</script>
<style lang="less" scoped>
  .header {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
    border-left: 3px solid rgba(var(--primary-6), 0.5);
    padding-left: 10px;
    .title {
      margin-right: 30px;
      width: 90px;
    }
  }
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
    .arco-select-view-single {
      padding: 0 5px;
    }
    .arco-input-wrapper {
      padding: 0 5px;
    }
    .arco-select-view-value {
      font-size: 12px !important;
      min-height: 26px;
    }
    .arco-input {
      font-size: 12px !important;
    }
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 5px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .order-w {
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
    }
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
</style>
